<template>
  <div class="database-accounts">
    <el-card class="accounts-card" shadow="hover">
      <div slot="header" class="card-header">
        <span><i class="el-icon-user"></i> 账号信息</span>
        <el-button type="primary" @click="showCreateAccountDialog" icon="el-icon-plus">创建账号</el-button>
      </div>

      <!-- 搜索栏 -->
      <div class="operation-bar">
        <div class="left-operations">
          <el-button-group>
            <el-button size="small" icon="el-icon-refresh" @click="refreshList">刷新</el-button>
          </el-button-group>
        </div>
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索账号"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch">
          </el-input>
        </div>
      </div>

      <!-- 账号列表 -->
      <el-table
        :data="filteredTableData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)"
        stripe>
        <el-table-column prop="username" label="账号" min-width="180">
          <template slot-scope="scope">
            <span class="username-text">{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="账号类型" min-width="150">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === '高权限账号' ? 'warning' : 'info'" effect="plain">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <div class="status-cell">
              <span class="status-dot" :class="{ 'active': scope.row.status === '可用' }"></span>
              {{ scope.row.status }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="database" label="所属数据库" min-width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.database || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="handleChangePassword(scope.row)">修改密码</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" @click="handleAuthorize(scope.row)">授权</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <span class="total-count">共 {{ total }} 条数据</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 创建账号对话框 -->
    <el-dialog
      title="创建账号"
      :visible.sync="createDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @closed="resetCreateForm">
      <el-form :model="createForm" :rules="createRules" ref="createForm" label-width="80px">
        <el-form-item label="账号" prop="username" required>
          <el-input
            v-model="createForm.username"
            placeholder="账号由小写字母、数字或下划线组成">
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input
            v-model="createForm.password"
            type="password"
            placeholder="密码由大小写字母、数字、特殊字符组成"
            show-password>
          </el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type" required>
          <el-radio-group v-model="createForm.type">
            <el-radio label="normal">普通账号</el-radio>
            <el-radio label="admin">高权限账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="form-tip" v-if="createForm.type === 'admin'">
          新创建的第一个账号的类型必须是高权限账号，且高权限账号仅能创建一个
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateSubmit" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      :visible.sync="passwordDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @closed="resetPasswordForm">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="新密码" prop="newPassword" required>
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password>
          </el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword" required>
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlePasswordSubmit" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DatabaseAccounts',
  data() {
    // 密码确认验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      // 搜索相关
      searchQuery: '',
      loading: false,

      // 表格数据
      tableData: [
        {
          username: 'tplus',
          type: '高权限账号',
          status: '可用',
          database: '--'
        }
      ],

      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 1,

      // 创建账号对话框
      createDialogVisible: false,
      submitting: false,
      createForm: {
        username: '',
        password: '',
        type: 'normal'
      },
      createRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { pattern: /^[a-z0-9_]+$/, message: '账号只能包含小写字母、数字或下划线', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, message: '密码长度不能小于8个字符', trigger: 'blur' },
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]+$/,
            message: '密码必须包含大小写字母、数字和特殊字符',
            trigger: 'blur'
          }
        ],
        type: [
          { required: true, message: '请选择账号类型', trigger: 'change' }
        ]
      },

      // 修改密码对话框
      passwordDialogVisible: false,
      passwordForm: {
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码长度不能小于8个字符', trigger: 'blur' },
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]+$/,
            message: '密码必须包含大小写字母、数字和特殊字符',
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    filteredTableData() {
      if (!this.searchQuery) {
        return this.tableData
      }
      const query = this.searchQuery.toLowerCase()
      return this.tableData.filter(data => {
        return data.username.toLowerCase().includes(query)
      })
    }
  },
  methods: {
    // 搜索相关方法
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 创建账号相关方法
    showCreateAccountDialog() {
      this.createDialogVisible = true
    },
    resetCreateForm() {
      if (this.$refs.createForm) {
        this.$refs.createForm.resetFields()
      }
      this.createForm = {
        username: '',
        password: '',
        type: 'normal'
      }
    },
    handleCreateSubmit() {
      this.$refs.createForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          // 模拟API调用
          setTimeout(() => {
            this.submitting = false
            this.createDialogVisible = false
            this.$message({
              message: '账号创建成功',
              type: 'success'
            })
            this.getList()
          }, 1000)
        }
      })
    },

    // 修改密码相关方法
    handleChangePassword(row) {
      this.currentAccount = row
      this.passwordDialogVisible = true
    },
    resetPasswordForm() {
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.resetFields()
      }
      this.passwordForm = {
        newPassword: '',
        confirmPassword: ''
      }
    },
    handlePasswordSubmit() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          // 模拟API调用
          setTimeout(() => {
            this.submitting = false
            this.passwordDialogVisible = false
            this.$message({
              message: '密码修改成功',
              type: 'success'
            })
          }, 1000)
        }
      })
    },

    // 授权相关方法
    handleAuthorize(row) {
      this.$message({
        message: '授权功能开发中',
        type: 'info'
      })
    },

    // 获取列表数据
    getList() {
      this.loading = true
      // 模拟API调用
      setTimeout(() => {
        this.loading = false
      }, 800)
    },

    // 刷新列表
    refreshList() {
      this.getList()
    }
  },
  created() {
    this.getList()
  }
}
</script>

<style scoped>
.database-accounts {
  padding: 0px;
}

.accounts-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header i {
  margin-right: 8px;
  font-size: 18px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-operations {
  display: flex;
  gap: 10px;
}

.search-box {
  width: 300px;
}

.username-text {
  font-family: monospace;
  color: #409EFF;
}

.status-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #909399;
}

.status-dot.active {
  background-color: #67C23A;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

/* 表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #E6A23C;
  margin-top: -10px;
  margin-bottom: 10px;
  padding-left: 80px;
}

/* 对话框样式优化 */
.el-dialog__header {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.el-dialog__footer {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}

.el-dialog__body {
  padding: 30px 20px;
}

/* 加载动画样式 */
.el-loading-spinner .el-icon-loading {
  font-size: 30px;
  color: #409EFF;
}

.el-loading-spinner .el-loading-text {
  color: #409EFF;
  margin: 3px 0;
  font-size: 14px;
}

/* 按钮间隔 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  padding: 0 8px;
}
</style>
